<template>
  <div class="phone-query">
    <!-- 输入框和按钮  -->
    <el-form :model="form" label-width="100px" class="demo-form-inline">
      <el-form-item label="电话号码">
        <el-input v-model="form.phone" placeholder="请输入电话号码"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="queryPhone">发送</el-button>
      </el-form-item>
    </el-form>

    <!-- 响应信息显示区域 -->
    <div class="response-area" v-if="responseMessage">
      <h3>响应信息</h3>
      <pre>{{ responseMessage }}</pre>
    </div>

    <!-- 新增：显示响应信息的框 -->
    <div class="response-box" v-if="responseData">
      <h3>详细响应数据</h3>
      <pre>{{ responseData }}</pre>
    </div>
  </div>
</template>

<script>
import { ElMessage } from "element-plus"; // 引入消息提示组件

export default {
  data() {
    return {
      form: {
        phone: "", // 电话号码
      },
      responseMessage: null, // 后端返回的简要响应信息
      responseData: null, // 后端返回的详细响应数据
    };
  },
  methods: {
    async queryPhone() {
      const phone = this.form.phone.trim();

      // 校验电话号码是否为空
      if (!phone) {
        ElMessage.error("请输入电话号码");
        return;
      }

      try {
        // 构造查询字符串
        const params = new URLSearchParams({ phone }).toString();

        // 调用后端接口，使用 GET 方法并将参数附加到 URL 中
        const response = await fetch(`/api/phone/location?${params}`, {
          method: "GET",
          headers: {
            "Content-Type": "application/json", // 没有实际作用 不影响
          },
        });

        // 处理响应
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        const data = await response.json();

        // 更新响应信息
        this.responseMessage = "请求成功，以下是详细数据：";
        this.responseData = JSON.stringify(data, null, 2); // 格式化显示详细响应数据
      } catch (error) {
        ElMessage.error(`请求失败：${error.message}`);
        this.responseMessage = `Error: ${error.message}`;
        this.responseData = null; // 清空详细响应数据
      }
    },
  },
};
</script>

<style scoped>
.phone-query {
  max-width: 600px;
  margin: 20px auto;
}

.response-area,
.response-box {
  margin-top: 20px;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  background-color: #f9f9f9;
}

.response-area pre,
.response-box pre {
  white-space: pre-wrap;
  word-wrap: break-word;
}
</style>